<template>
  <div>
    <!-- 上传excel -->
    <el-upload
      :ref="(el) => handleSetUploadRefMap(el)"
      action=""
      :http-request="httpExcelRequest"
      :limit="1"
      :show-file-list="false"
      class="uploadExcelContent"
    >
      <div title="导入excel" style="cursor: pointer">
        <div>{{ props.name }}</div>
      </div>
    </el-upload>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <el-button @click="importExcel" style="left: 30px">导入</el-button>
      <el-card>
        <div
          class="excel-content"
          v-for="(rowItem, rowIndex) in excelList"
          :key="rowIndex"
        >
          <div
            class="comp"
            v-for="(comp, compIndex) in rowItem"
            :key="compIndex"
          >
            <div v-if="props.CheckWords(comp)" style="color: red">
              {{ comp }}
            </div>
            <div v-else>
              {{ comp }}
            </div>
          </div>
        </div>
      </el-card>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { importExcelFileApi } from "@/api/file";

defineOptions({
  name: "Upload",
  inheritAttrs: false,
});

import * as xlsx from "xlsx";
import { ref } from "vue";
const uploadRefMap = ref<{ [key: string]: any }>({});
const excelList = ref<any[]>([]);
let flag = true;

/**
 * 组件传递内容
 */
const props = defineProps({
  name: String,
  table: String,
  CheckWords: {
    type: Function as PropType<(word: string) => boolean>,
    required: true,
  },
});

/**
 * 弹窗对象
 */
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 1200,
  title: "",
});

/**
 * 关闭弹窗
 **/
function closeDialog() {
  dialog.visible = false;
}

/**
 * 动态配置上传REF
 * @param el
 */
const handleSetUploadRefMap = (el: any) => {
  if (el) {
    uploadRefMap.value[`Upload_Ref`] = el;
  }
};

/**
 * 文件上传自定义
 * @param op
 */
const httpExcelRequest = async (op: any) => {
  // 获取除文件之外的参数，具体根据实际业务需求来
  // console.log(op.data);
  // 获取上传的excel  并解析数据
  let file = op.file;
  let dataBinary = await readFile(file);
  let workBook = xlsx.read(dataBinary, { type: "binary", cellDates: true });
  let workSheet = workBook.Sheets[workBook.SheetNames[0]];
  const excelData = xlsx.utils.sheet_to_json(workSheet, { header: 1 });
  excelList.value = excelData;
  // console.log(excelData);
  if (uploadRefMap.value[`Upload_Ref`]) {
    uploadRefMap.value[`Upload_Ref`].clearFiles();
  }
};

/**
 * 读取excel文件
 * @param file
 */
const readFile = (file: any) => {
  return new Promise((resolve) => {
    let reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = (ev) => {
      resolve(ev.target?.result);
    };
    dialog.visible = true;
  });
};

/**
 * 导入excel
 */
const importExcel = () => {
  const table = String(props.table);
  if (!table) {
    ElMessage.warning("未选择导入表名称！");
    return;
  }
  ElMessageBox.confirm("确认导入该数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    importExcelFileApi(table, excelList.value).then(() => {
      ElMessage.success("导入成功");
      closeDialog();
    });
  });
};
</script>

<style lang="scss" scoped>
.uploadExcelContent {
  display: flex;
  flex-direction: row;
}
.excel-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  .comp {
    width: 200px;
    font-size: 12px;
  }
}
</style>
